package cc.rengu.igas.opms.core.service.trans.common;

import cc.rengu.igas.opms.common.enums.RespCodeEnum;
import cc.rengu.igas.opms.common.util.QrCodeUtil;
import cc.rengu.igas.opms.core.service.base.ManageService;
import cc.rengu.igas.opms.facade.bean.OrderInfoBean;
import cc.rengu.igas.opms.facade.bean.PayAcctInfoBean;
import cc.rengu.igas.opms.facade.request.PayOrderInfoQueryRequest;
import cc.rengu.igas.opms.facade.response.PayOrderInfoQueryResponse;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.model.PlatMchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.UserService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.igas.share.core.realize.impl.UserServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.MchntOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.PayOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.UserOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.MchntOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.PayOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.UserOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;


import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 * 支付订单详情查询
 * CREATE BY fuyp
 * modify by wangcheng 2021-09-13
 */
public class PayOrderInfoQueryService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        //加载查询支付订单详情请求类
        PayOrderInfoQueryRequest payOrderInfoQueryRequest = new PayOrderInfoQueryRequest();
        ConvertUtil.convertOutput(payOrderInfoQueryRequest);
        return payOrderInfoQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        BizResponse bizResponse = new BizResponse();
        PayOrderInfoQueryRequest payOrderInfoQueryRequest = (PayOrderInfoQueryRequest) request;
        OrderInfoBean orderInfoBean = new OrderInfoBean();

        /*校验用户订单号和订单二维码不可同时为空 */
        if (StringUtil.isEmptyOrNull(payOrderInfoQueryRequest.getUserOrderId()) &&
                StringUtil.isEmptyOrNull(payOrderInfoQueryRequest.getQrCodeUrl())) {
            rglog.error("用户订单号和订单二维码不可同时为空");
            throw new BizException(RespCodeEnum.MCHNTORDERNOANDQRCODEURL_NOT_BLANK.getRespCode(), RespCodeEnum.MCHNTORDERNOANDQRCODEURL_NOT_BLANK.getRespDesc());
        }

        /*查询用户订单表*/
        rglog.debug("流程日志-获取用户订单，可根据用户订单号和二维码信息查询....");
        UserOrderInfo userOrderInfo;
        /*用户订单号不为空*/
        if (!StringUtil.isEmptyOrNull(payOrderInfoQueryRequest.getUserOrderId())) {
            /*根据订单号查询用户订单信息*/
            UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();
            userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByUserOrderId(payOrderInfoQueryRequest.getHeader().getInstId(), payOrderInfoQueryRequest.getUserOrderId());
            if (userOrderInfo == null) {
                rglog.error("用户支付订单不存在");
                throw new BizException(RespCodeEnum.ORDER_NOEXIT.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
            }
        } else {
            UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();
            String qrUrl = payOrderInfoQueryRequest.getQrCodeUrl();
            //去掉C1码中的tt和si参数
            qrUrl = QrCodeUtil.filterTtAndSi(qrUrl);
            /*判断是否银标码：收银台域名?qrCode=https//95516.com/xxxx*/
            if (qrUrl.contains("qr.95516.com")) {
                int qrIndex = qrUrl.indexOf("qrCode=");
                if (qrIndex < 0) {
                    rglog.error("无效二维码<{}>", qrUrl);
                    throw new BizException(RespCodeEnum.GET_QRCODE_INVALID.getRespCode(), RespCodeEnum.GET_QRCODE_INVALID.getRespDesc());
                }
                qrUrl = qrUrl.substring(qrIndex + 7);
                /*银联回调时url编码了,此时urldecode*/
                qrUrl = URLDecoder.decode(qrUrl, "UTF-8");
            }
            rglog.info("实际二维码url<{}>", qrUrl);
            /*根据订单二维码查询订单信息*/
            userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByOrderUrl(payOrderInfoQueryRequest.getHeader().getInstId(), qrUrl);
        }
        if (null == userOrderInfo) {
            rglog.error("用户订单不存在");
            throw new BizException(RespCodeEnum.USERORDER_INVALID.getRespCode(), RespCodeEnum.USERORDER_INVALID.getRespDesc());
        }

        /*比较订单金额*/
        if (!StringUtil.isEmptyOrNull(payOrderInfoQueryRequest.getOrderAmt()) && 0 != AmountUtil.compare(payOrderInfoQueryRequest.getOrderAmt(), userOrderInfo.getOrderAmt())) {
            rglog.error("订单金额不一致，requestOrderAmt:<{}>,userOrderAmt:<{}>", payOrderInfoQueryRequest.getOrderAmt(), userOrderInfo.getOrderAmt());
            throw new BizException(RespCodeEnum.USERORDER_INVALID.getRespCode(), RespCodeEnum.USERORDER_INVALID.getRespDesc());
        }

        /*查询用户订单信息*/
        rglog.debug("流程日志-获取用户订单....");
        MchntInfo mchntInfo;
        MchntService mchntService = new MchntServiceImpl();
        MchntOrderInfoMapper mchntOrderInfoMapper = new MchntOrderInfoMapperImpl();
        List<MchntOrderInfo> mchntOrderInfoList = mchntOrderInfoMapper.selectMchntOrderInfoBySysSeqNum(payOrderInfoQueryRequest.getHeader().getInstId(), userOrderInfo.getSysSeqNum());
        if (null == mchntOrderInfoList || mchntOrderInfoList.size() == 0) {
            rglog.error("商户订单信息不存在");
            throw new BizException(RespCodeEnum.USERORDER_INVALID.getRespCode(), RespCodeEnum.USERORDER_INVALID.getRespDesc());
        } else {
            if ("00".equals(mchntOrderInfoList.get(0).getBizSceneType()) || "02".equals(mchntOrderInfoList.get(0).getBizSceneType())) {
                /*购买卡券特殊处理*/
                mchntInfo = mchntService.getMchntInfo(payOrderInfoQueryRequest.getHeader().getInstId(), mchntOrderInfoList.get(0).getMchntNo());
                if (null == mchntInfo) {
                    rglog.error("基本商户不存在或商户非正式商户");
                    throw new BizException(RespCodeEnum.PLATMCHNT_NOT_BLANK.getRespCode(), RespCodeEnum.PLATMCHNT_NOT_BLANK.getRespDesc());
                }
                /* 非合并订单支付时校验上传的商户与下单的商户是否一致 */
                if (!StringUtil.isEmptyOrNull(payOrderInfoQueryRequest.getPlatMchntNo())) {
                    if (!StringUtil.isEmptyOrNull(payOrderInfoQueryRequest.getPlatMchntNo()) && !userOrderInfo.getGroupMchntNo().equals(payOrderInfoQueryRequest.getPlatMchntNo())) {
                        rglog.info("上传的商户:<{}>与下单的商户:<{}>或商户所属平台商户:<{}>均不一致",
                                payOrderInfoQueryRequest.getPlatMchntNo(), mchntOrderInfoList.get(0).getMchntNo(), mchntInfo.getPlatMchntNo());
                        throw new BizException(RespCodeEnum.MCHNT_DISACCORD.getRespCode(), RespCodeEnum.MCHNT_DISACCORD.getRespDesc());
                    }
                }
                orderInfoBean.setMchntNo(mchntInfo.getMchntNo());
                orderInfoBean.setMchntName(mchntInfo.getMchntName());
                orderInfoBean.setRefundAmt(mchntOrderInfoList.get(0).getRefundAmt());
            } else {
                if (mchntOrderInfoList.size() > 1 || !StringUtil.isEmptyOrNull(userOrderInfo.getGroupMchntNo())) {
                    rglog.debug("合并订单支付时通过用户表中平台商户号:<{}>获取平台商户信息....", userOrderInfo.getGroupMchntNo());
                    /* 合并支付的时候上送的商户号必须是平台商户号 */
                    if (!StringUtil.isEmptyOrNull(payOrderInfoQueryRequest.getPlatMchntNo()) && !userOrderInfo.getGroupMchntNo().equals(payOrderInfoQueryRequest.getPlatMchntNo())) {
                        rglog.info("合并支付上送商户号与用户订单表中记录的平台商户号不一致，requestMchntNo:<{}>,userOrderPlatMchntNo:<{}>", payOrderInfoQueryRequest.getPlatMchntNo(), userOrderInfo.getGroupMchntNo());
                        throw new BizException(RespCodeEnum.ORDER_NOEXIT.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
                    }
                    /*合并订单支付 取平台商户信息*/
                    PlatMchntInfo platMchntInfo = mchntService.getPlatMchntInfo(payOrderInfoQueryRequest.getHeader().getInstId(), userOrderInfo.getGroupMchntNo());
                    if (null == platMchntInfo) {
                        rglog.error("平台商户信息不存在或商户非正式商户");
                        throw new BizException(RespCodeEnum.PLATMCHNT_NOT_BLANK.getRespCode(), RespCodeEnum.PLATMCHNT_NOT_BLANK.getRespDesc());
                    }
                    orderInfoBean.setMchntNo(platMchntInfo.getPlatMchntNo());
                    orderInfoBean.setMchntName(platMchntInfo.getPlatMchntName());
                    orderInfoBean.setRefundAmt(countRefundAmt(mchntOrderInfoList));
                } else {
                    /*非合并订单 取进商户基本信息 */
                    mchntInfo = mchntService.getMchntInfo(payOrderInfoQueryRequest.getHeader().getInstId(), mchntOrderInfoList.get(0).getMchntNo());
                    if (null == mchntInfo) {
                        rglog.error("基本商户不存在或商户非正式商户");
                        throw new BizException(RespCodeEnum.PLATMCHNT_NOT_BLANK.getRespCode(), RespCodeEnum.PLATMCHNT_NOT_BLANK.getRespDesc());
                    }
                    /* 非合并订单支付时校验上传的商户与下单的商户是否一致 */
                    if (!StringUtil.isEmptyOrNull(payOrderInfoQueryRequest.getPlatMchntNo())) {
                        if (!payOrderInfoQueryRequest.getPlatMchntNo().equals(mchntOrderInfoList.get(0).getMchntNo())
                                && !payOrderInfoQueryRequest.getPlatMchntNo().equals(mchntInfo.getPlatMchntNo())) {
                            rglog.info("上传的商户:<{}>与下单的商户:<{}>或商户所属平台商户:<{}>均不一致",
                                    payOrderInfoQueryRequest.getPlatMchntNo(), mchntOrderInfoList.get(0).getMchntNo(), mchntInfo.getPlatMchntNo());
                            throw new BizException(RespCodeEnum.MCHNT_DISACCORD.getRespCode(), RespCodeEnum.MCHNT_DISACCORD.getRespDesc());
                        }
                    }
                    orderInfoBean.setMchntNo(mchntInfo.getMchntNo());
                    orderInfoBean.setMchntName(mchntInfo.getMchntName());
                    orderInfoBean.setRefundAmt(mchntOrderInfoList.get(0).getRefundAmt());
                }
            }
        }

        /*查询支付订单信息*/
        PayOrderInfoMapper payOrderInfoMapper = new PayOrderInfoMapperImpl();
        PayAcctInfoBean payAcctInfoBean = new PayAcctInfoBean();
        List<PayOrderInfo> payOrderInfoList = payOrderInfoMapper.selectPayOrderInfoBySysSeqNum(payOrderInfoQueryRequest.getHeader().getInstId(), userOrderInfo.getSysSeqNum());
        String payAcctNo = "";
        if (null != payOrderInfoList && !payOrderInfoList.isEmpty()) {
            payOrderInfoList = payOrderInfoList.stream().filter(item -> !ChannelEnum.ACCT.getChannelType().equals(item.getMsgDstId())
                    && !ChannelEnum.MOMP.getChannelType().equals(item.getMsgDstId())).collect(Collectors.toList());
            if (!payOrderInfoList.isEmpty()) {
                payAcctInfoBean.setTranAmt(payOrderInfoList.get(0).getRealPayAmt());
                payAcctInfoBean.setPayType(payOrderInfoList.get(0).getPayType());
                payAcctInfoBean.setPayerAcctType(payOrderInfoList.get(0).getPayerAcctType());
                payAcctInfoBean.setPayerAcctInfo(payOrderInfoList.get(0).getPayerAcctInfo());
                payAcctNo = payOrderInfoList.get(0).getPayerAcctInfo();
            }
        }
        /*为订单信息赋值*/
        orderInfoBean.setDiscountAmt(userOrderInfo.getRealDiscountAmt());
        orderInfoBean.setPayAcctInfo(payAcctInfoBean);
        orderInfoBean.setTransDate(userOrderInfo.getTxnDate());
        orderInfoBean.setTransTime(userOrderInfo.getTxnTime());
        orderInfoBean.setTxnNum(userOrderInfo.getTxnNum());
        orderInfoBean.setMchntOrderId(userOrderInfo.getMchntOrderId());
        orderInfoBean.setPayAcctNo(payAcctNo);
        orderInfoBean.setOrderCcy(userOrderInfo.getOrderCcy());
        orderInfoBean.setOrderAmt(userOrderInfo.getOrderAmt());
        orderInfoBean.setRealPayAmt(userOrderInfo.getRealPayAmt());
        orderInfoBean.setOrderExpiryTime(userOrderInfo.getOrderExpiryTime());
        orderInfoBean.setOrderStatus(userOrderInfo.getOrderStatus());
        orderInfoBean.setBizStatus(userOrderInfo.getBizStatus());
        orderInfoBean.setOrderDesc(userOrderInfo.getOrderDesc());
        rglog.debug("订单附加信息:<{}>中如果有核心客户号放入用户会话中", userOrderInfo.getOrderExtraInfo());
        /* 订单附加信息中如果有核心客户号存入session中 */
        UserService userService = new UserServiceImpl();
        if (!StringUtil.isEmptyOrNull(userOrderInfo.getOrderExtraInfo())) {
            Map<String, String> orderExtraInfo = JSON.parseObject(userOrderInfo.getOrderExtraInfo(), Map.class);
            String coreCustomerId = "";
            for (String key : orderExtraInfo.keySet()) {
                if ("coreCustomerId".equals(key)) {
                    coreCustomerId = orderExtraInfo.get(key);
                    break;
                }
            }
            if (!StringUtil.isEmptyOrNull(coreCustomerId)) {
                userService.setUserSessionValue("coreCustomerId", coreCustomerId);
            }
        }
        //响应信息
        PayOrderInfoQueryResponse payOrderInfoQueryResponse = new PayOrderInfoQueryResponse();
        payOrderInfoQueryResponse.setOrderInfo(orderInfoBean);
        payOrderInfoQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        payOrderInfoQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setResult(payOrderInfoQueryResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        PayOrderInfoQueryResponse payOrderInfoQueryResponse = (PayOrderInfoQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(payOrderInfoQueryResponse);
    }

    /**
     * 累加退款金额
     *
     * @param mchntOrderInfoList 商户订单信息
     * @return 累计退款金额
     */
    private String countRefundAmt(List<MchntOrderInfo> mchntOrderInfoList) {
        String totleRefundAmt = "0";
        for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
            if (!StringUtil.isEmptyOrNull(mchntOrderInfo.getRefundAmt())) {
                totleRefundAmt += AmountUtil.addition(totleRefundAmt, mchntOrderInfo.getRefundAmt());
            }
        }
        return totleRefundAmt;
    }
}
